import {addPmGroup, editPmGroup, selectAllProgressTem, selectPmGroupById} from '@/api/evalutaion'
import Evaluation from '@/components/others/evalutaion'
import {useLoading} from '@/hooks/loading'
import useGlobalAPI from '@/hooks/useGlobalAPI'
import {ant_design_vue} from '@/libs/global/antDesignVue'
import {goBack, toHome} from '@/libs/pageRedirect'
import {defineComponent, reactive, watch, onMounted, onUnmounted} from 'vue'
const {message} = ant_design_vue

export default defineComponent({
  setup(props, ctx) {
    const {route} = useGlobalAPI()
    const {loading, closeLoading, startLoading} = useLoading()
    let state = reactive<{
      evalutaion: Evaluation.EvalutaionData
      reloadTime: NodeJS.Timeout | undefined
      pmGroupId: number
    }>({
      evalutaion: {
        appointScoreSwitch: 0,
        partakeCount: 0,
        pmGroupId: -1,
        createTime: '',
        /**考核表名称 */
        pmGroupName: '',
        /**周期类型code */
        pmPeriodCode: '0025',
        /**考核组备注 */
        pmGroupDesc: '',
        /**周期类型名称 */
        pmPeriodName: '月度',
        /**考核组人员列表 */
        pmGroupUserList: [],
        /**考核组部门列表 */
        pmGroupDeptList: [],
        /**考核组绩效列表 */
        pmGroupDimensionList: [],
        /**考核组流程列表 */
        pmGroupProgressList: [],
        pmGroupExcUserList: []
      },
      reloadTime: undefined,
      pmGroupId: -1
    })

    /**监听考核表内容变化 state.evalutaion */
    watch(
      () => state.evalutaion,
      n => {
        console.log('添加考评组 考评组数据变化', n)
      },
      {deep: true}
    )

    function getPageData() {
      startLoading()
      selectPmGroupById({pmGroupId: state.pmGroupId})
        .then(res => {
          state.evalutaion = res.data
          closeLoading()
        })
        .catch(err => {
          closeLoading()
        })
    }

    // function combPmGroupProgressListByProgressTem(
    //   data: Evaluation.Progress[]
    // ): Evaluation.PmGroupProgress[] {
    //   return data.map(item => ({
    //     pmGroupProgressId: item.pmGroupProgressTemId,
    //     pmGroupId: -1,
    //     pmGroupProgressName: item.pmGroupProgressTemName,
    //     pmGroupProgressStatus:
    //       item.pmGroupProgressTemStatus,
    //     pmGroupStageCode: item.pmGroupStageCode,
    //     isMakeProgress: item.isMakeProgress,
    //     sort: item.sort,
    //     pmProgressSetList:
    //       combPmProgressSetListByProgressTem(
    //         item.pmProgressSetTemList
    //       )
    //   }))
    // }

    // function combPmProgressSetListByProgressTem(
    //   data: Evaluation.PmProgressSetTem[]
    // ): Evaluation.PmProgressSet[] {
    //   if (!data) return []
    //   return data.map(item => ({
    //     pmGroupProgressSetId: item.pmGroupProgressSetTemId,
    //     pmGroupProgressId: -1,
    //     pmGroupProgressSetName:
    //       item.pmGroupProgressSetTemName,
    //     pmGroupProgressSetEngName:
    //       item.pmGroupProgressSetTemEngName,
    //     sort: item.sort,
    //     parentId: item.parentId,
    //     pmGroupProgressSetValue:
    //       item.pmGroupProgressSetTemValue,
    //     pmGroupProgressSetTemAdditionalValue:
    //       item.pmGroupProgressSetTemAdditionalValue,
    //     pmGroupProgressSetList:
    //       !item.pmGroupProgressSetTemList ||
    //       !item.pmGroupProgressSetTemList.length
    //         ? []
    //         : combPmProgressSetListByProgressTem(
    //             item.pmGroupProgressSetTemList
    //           )
    //   }))
    // }

    function handleConfirm() {
      if (!state.evalutaion.pmGroupName) {
        message.warning({
          content: '请输入考评组名称'
        })
        return
      }

      if (!state.evalutaion.pmGroupDeptList.length && !state.evalutaion.pmGroupUserList.length) {
        message.warning({
          content: '未选择考评员工'
        })
        return
      }

      if (!state.evalutaion.pmGroupDimensionList.length) {
        message.warning({
          content: '模板指标中的维度为空！'
        })
        return
      }

      for (let i = 0; i < state.evalutaion.pmGroupProgressList.length; i++) {
        const pmGroupProgress = state.evalutaion.pmGroupProgressList[i]

        if (
          pmGroupProgress.pmGroupStageCode === '0017' ||
          pmGroupProgress.pmGroupStageCode === '0018'
        ) {
          if (pmGroupProgress.pmProgressSetList) {
            for (let ii = 0; ii < pmGroupProgress.pmProgressSetList.length; ii++) {
              const pmProgressSet = pmGroupProgress.pmProgressSetList[ii]
              if (
                pmProgressSet.pmGroupProgressSetEngName === 'confirmUser' ||
                pmProgressSet.pmGroupProgressSetEngName === 'scoreUser'
              ) {
                if (pmProgressSet.pmGroupProgressSetList) {
                  for (let iii = 0; iii < pmProgressSet.pmGroupProgressSetList.length; iii++) {
                    const pmGroupProgressSet = pmProgressSet.pmGroupProgressSetList[iii]
                    if (pmGroupProgressSet.pmGroupProgressSetValue === '1') {
                      switch (pmProgressSet.pmGroupProgressSetEngName) {
                        case 'confirmUser':
                          break
                        case 'scoreUser':
                          switch (pmGroupProgressSet.pmGroupProgressSetEngName) {
                            case 'scoreAppointEmployee':
                              if (pmGroupProgressSet.pmGroupProgressSetTemAdditionalValue) {
                                let userInfoList =
                                  pmGroupProgressSet.pmGroupProgressSetTemAdditionalValue.split(';')

                                for (let j = 0; j < userInfoList.length; j++) {
                                  const userInfo = userInfoList[j].split(',')[0]

                                  let userWeight = Number(userInfoList[j].split(',')[1])

                                  if (!userWeight || userWeight !== userWeight) {
                                    message.warning(
                                      '给指定评分人：' + userInfo.split('-')[1] + ', 没有输入权重'
                                    )
                                    return
                                  }
                                }
                              } else {
                                message.warning('考评流程中上级评分的指定人员未选择')
                                return
                              }
                              break
                            case 'scoreLeader':
                              if (pmGroupProgressSet.pmGroupProgressSetTemAdditionalValue) {
                                let userInfoList =
                                  pmGroupProgressSet.pmGroupProgressSetTemAdditionalValue.split(';')

                                for (let j = 0; j < userInfoList.length; j++) {
                                  const leader = userInfoList[j].split(',')[0]

                                  let leaderWeight = Number(userInfoList[j].split(',')[1])

                                  if (!leaderWeight || leaderWeight !== leaderWeight) {
                                    message.warning(
                                      (leader == '1' ? '直属主管' : leader + '级主管') +
                                        '没有输入权重'
                                    )
                                    return
                                  }
                                }
                              } else {
                                message.warning('考评流程中上级评分的主管未选择')
                                return
                              }
                              break
                            default:
                              break
                          }
                          break
                        default:
                          break
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }

      // 修改维度-指标的自评模板字段名
      // state.evalutaion.pmGroupDimensionList.forEach((item1, index1) => {
      //   item1.pmGroupDimensionTargetList.forEach((item2, index2) => {
      //     item2.pmGroupDimensionSelfContentTem = item2.selfContentTem
      //     delete item2.selfContentTem
      //   })
      // })
      console.log('考评组数据save', state.evalutaion)
      startLoading()
      editPmGroup(state.evalutaion)
        .then(res => {
          message.success({
            content: '考评组修改成功！'
          })
          const timer = setTimeout(() => {
            closeLoading()
            location.reload()
            goBack()
          }, 800)
          state.reloadTime = timer
        })
        .catch(err => {
          if (err && err.msg)
            message.warning({
              content: '考评组修改失败!'
            })

          closeLoading()
        })
    }

    onMounted(() => {
      let params = route.query
      let paramsKeys = Object.keys(params)
      if (paramsKeys.indexOf('pmGroupId') === -1) {
        goBack()
        return
      }

      let pmGroupId = Number(params.pmGroupId || 0)

      if (pmGroupId !== pmGroupId) {
        goBack()
        return
      }
      state.pmGroupId = pmGroupId === pmGroupId ? pmGroupId : -1
      getPageData()
    })

    onUnmounted(() => {
      // @ts-ignore
      state.reloadTime && clearTimeout(state.reloadTime)
    })

    return () => (
      <Evaluation
        title='修改考评组'
        v-model={[state.evalutaion, 'evalutaion']}
        onConfirm={handleConfirm}
        loading={loading.value}
        showAppointScore={false}
      ></Evaluation>
    )
  }
})
